
<template>
  <div class="content">
    <el-form ref="form" :model="form" label-width="100px" size="mini" :inline="true">

      <el-form-item label="起止时间：">
        <el-date-picker
          v-model="form.startTime"
          type="datetime"
          style="width:180px"
          size="mini"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择日期">
        </el-date-picker>
        -
        <el-date-picker
          v-model="form.endTime"
          type="datetime"
          style="width:180px"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="学校：" v-show="showSchool">
        <el-select
          clearable
          v-model="form.deptId"
          @change="gradeList(form.deptId)"
          placeholder="请选择所属学校"
          size="mini"
          style="width:150px"
        >
          <el-option :label="item.name" :value="item.id" v-for="item in schoolList" :key="item.id"></el-option>
        </el-select>
      </el-form-item>


      <el-form-item label="档口：">
        <el-select
          clearable
          v-model="form.dangkouId"
          placeholder="请选择档口"
          size="mini"
          style="width:150px"
        >
          <el-option
            :label="item.name"
            :value="item.id"
            v-for="(item,index) in dangkou"
            :key="index"
          ></el-option>
        </el-select>

      </el-form-item>

      <el-form-item label="年级：" v-show="showClassStatus">
        <el-select
          clearable
          v-model="form.glassId"
          @change="classList(form.glassId)"
          placeholder="请选择年级"
          size="mini"
          style="width:150px"
        >
          <el-option
            :label="item.name"
            :value="item.id"
            v-for="(item,index) in gradeData"
            :key="index"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="班级：" v-show="showClassStatus">
        <el-select clearable v-model="form.classId" placeholder="请选择班级" size="mini" style="width:150px">
          <el-option
            :label="item.name"
            :value="item.id"
            v-for="(item,index) in classData"
            :key="index"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-button type="primary" size="mini" @click="common" class="btn"><i class="fa fa-search"
                                                                           style="margin-right:5px;"></i>查询
      </el-button>
<!--      <el-button type="primary" @click="excelExport" size="mini"><i class="fa fa-arrow-down"-->
<!--                                                                    style="margin-right:5px;"></i>导出-->
<!--      </el-button>-->

    </el-form>


    <div class="title">{{dateStart}} - {{dateEnd}}<span>档口消费统计报表</span></div>
    <template>
      <el-table :data="tableData" v-loading="loading" show-summary size="mini" style="width: 100%;margin-top:30px">
        <el-table-column prop="shopName" fixed label="档口名称"></el-table-column>
        <el-table-column header-align="center" align="center" label="早餐">
          <el-table-column prop="zcCount" label="次数" header-align="center" align="center"></el-table-column>
          <el-table-column prop="zcAmt" label="金额" header-align="center" align="center"></el-table-column>
        </el-table-column>
      <el-table-column   header-align="center" align="center" label="午餐">
          <el-table-column prop="wcCount" label="次数" header-align="center" align="center"></el-table-column>
          <el-table-column prop="wcAmt" label="金额" header-align="center" align="center"> </el-table-column>
      </el-table-column>
      <el-table-column  header-align="center" align="center" label="晚餐">
          <el-table-column prop="wacCount" label="次数" header-align="center" align="center"> </el-table-column>
          <el-table-column prop="wacAmt" label="金额" header-align="center" align="center"></el-table-column>
      </el-table-column> -->
      <el-table-column  header-align="center" align="center" label="全天">
          <el-table-column prop="totalCount" label="次数" header-align="center" align="center"></el-table-column>
          <el-table-column prop="allAmt" label="金额" header-align="center" align="center"> </el-table-column>
     </el-table-column>
      </el-table>
    </template>
  </div>
</template>

<script>
  import Cookies from 'js-cookie'

  export default {
    name: 'Recharge',

    data() {
      return {
        url: this.$Config.url,
        loading: false,//表格加载中控制
        showClassStatus: false,//控制年纪班级展示

        schoolList: [],//学校列表
        gradeData: [],//年纪列表
        classData: [],//班级列表

        form: {
          deptId: '',//选中的学校
          glassId: '',//选中的年级
          classId: '',//选中的班级

          startTime: '',//查询开始时间
          endTime: '',//查询结束时间
          classStatus: '',//选中的当前类型
          eatTime:"",//就餐时段
          dangkouId:"",//档口id
        },
        tableData: [],
        dangkou:[],
        showSchool: true//控制学校的显示隐藏
      }
    },
    computed: {
      dateStart() {
        if (typeof this.form.startTime == 'object') {
          return this.$Config.dateFormat(this.form.startTime)
        } else {
          return this.form.startTime
        }
      },
      dateEnd() {
        if (typeof this.form.endTime == 'object') {
          return this.$Config.dateFormat(this.form.endTime)
        } else {
          return this.form.endTime
        }
      },
      className() {
        if (this.form.classStatus == '') {
          return '全部'
        } else if (this.form.classStatus == '1') {
          return '学生'
        } else if (this.form.classStatus == '2') {
          return '教师'
        } else {
          return '访客'
        }
      },
      areaTime(){
        return this.form.eatTime;
      }
    },
    mounted() {
      this.form.startTime = new Date(this.$Config.getTime())
      this.form.endTime = new Date()
      const deptId = JSON.parse(localStorage.getItem('userInfo')).deptId
      if (deptId) {
        this.form.deptId = deptId
        this.showSchool = false
        this.gradeList(deptId)
      } else {
        this.showSchool = true
        this.getSchool()
      }
      // this.common()
        this.getDang()
    },
    methods: {
      getDang(){
        const that = this
        const requestData={
          pageNo: 1,
          pageSize: 99999
        }
        this.$axios
          .get(that.url + '/admin/shop/page', {
            params: requestData,
            headers: {
              'x-baie-admin-token': Cookies.get('token')
            }
          })
          .then(function(res) {
            if (res.data.code == 200) {
              that.dangkou = res.data.data.records
            } else {
              that.$message({
                message: res.data.msg,
                type: 'warning'
              })
            }
          })
          .catch(function(error) {
            console.log(error)
          })
      },
      /**
       * 导出
       */
      excelExport() {
        let deptIdNew="";

        const deptId = JSON.parse(localStorage.getItem("userInfo")).deptId;

        if(deptId==null){//管理员登录
          if(this.form.deptId==""){
            this.$message({
              message: '请先选择学校',
              type: 'warning'
            });
            return
          }else{
            deptIdNew=this.form.deptId
          }
        }else{
          deptIdNew=deptId
        }

        var divFrame = window.parent.document.getElementById(
          "downLoadListFrame"
        );
        //判断是否存在，如果存在先移除，再重新创建
        if (divFrame != null) {
          window.parent.document.body.removeChild(divFrame);
        }
        var iframe = window.parent.document.createElement("iframe");
        iframe.setAttribute("id", "downLoadListFrame");
        //download_file.id = "downFrame";
        window.parent.document.body.appendChild(iframe);
        divFrame = window.parent.document.getElementById("downLoadListFrame");
        //隐式调用，（注意：window.parent.document 适应对于，farme内部代码，调用frame 外部dom；如果项目未用frame，改写成 document即可）
        divFrame.src = `${this.url}/admin/orderinfo/data/export?deptId=${deptIdNew}`;
        divFrame.style.display = "none";

      },
      /**
       * 查询学校
       */
      getSchool() {
        const that = this
        this.$axios
          .get(that.url + '/admin/dept/list', {
            headers: {
              'x-baie-admin-token': Cookies.get('token')
            }
          })
          .then(function(res) {
            if (res.data.code == 200) {
              that.schoolList = res.data.data
            } else {
              that.$message({
                message: res.data.msg,
                type: 'warning'
              })
            }
          })
          .catch(function(error) {
            console.log(error)
          })
      },
      gradeList(id) {
        console.log(id)
        const that = this
        this.$axios
          .get(that.url + '/admin/grade/list', {
            params: {
              deptId: id
            },
            headers: {
              'x-baie-admin-token': Cookies.get('token')
            }
          })
          .then(function(res) {
            if (res.data.code == 200) {
              that.gradeData = res.data.data

              console.log(res.data.data)
            } else {
              that.$message({
                message: res.data.msg,
                type: 'warning'
              })
            }
          })
          .catch(function(error) {
            console.log(error)
          })
      },
      classList(id) {
        const that = this
        that.form.classId = ''
        this.$axios
          .get(that.url + '/admin/class/list', {
            params: {
              gradeId: id
            },
            headers: {
              'x-baie-admin-token': Cookies.get('token')
            }
          })
          .then(function(res) {
            if (res.data.code == 200) {
              that.classData = res.data.data
            } else {
              that.$message({
                message: res.data.msg,
                type: 'warning'
              })
            }
          })
          .catch(function(error) {
            console.log(error)
          })
      },
      /**
       * 选择老师 学生 还是访客
       */
      checkClass() {
        if (this.form.classStatus == '1') {//筛选到学生
          this.showClassStatus = true
        } else {
          this.showClassStatus = false

          //  清空 年级班级
          this.form.glassId = ''
          this.form.classId = ''
        }

      },
      common(pageNo = 1, pageSize = 10) {
        const that = this
        that.loading = true
        const requestData = {
          deptId: this.form.deptId,//机构id
          startTime: typeof this.form.startTime == 'object' ? this.$Config.dateFormat(this.form.startTime) : this.form.startTime,//开始时间
          endTime: typeof this.form.endTime == 'object' ? this.$Config.dateFormat(this.form.endTime) : this.form.endTime,//结束时间
          shopId:this.form.dangkouId
        }
        this.$axios
          .get(that.url + '/admin/shop/data/report', {
            params: requestData,
            headers: {
              'x-baie-admin-token': Cookies.get('token')
            }
          })
          .then(function(res) {
            that.loading = false
            if (res.data.code == 200) {
              // that.tableData = res.data.data
              that.resetData(res.data.data);
            } else {
              that.$message({
                message: res.data.msg,
                type: 'warning'
              })
            }
          })
          .catch(function(error) {
            that.loading = false
            console.log(error)
          })
      },
      resetData(data){
        let tempArr = [], newArr = []
        console.log('--------1------------');
        for (let i = 0; i < data.length; i++) {
          console.log('--------2------------');
          if (tempArr.indexOf(data[i].shopName) === -1) {
            console.log('--------3------------');
            console.log(data[i].shopName +':'+data[i]);
            newArr.push(data[i])
            tempArr.push(data[i].shopName);
          } else {
            for (let j = 0; j < newArr.length; j++) {
              if (newArr[j].shopName == data[i].shopName) {//先判断是学生 老师 还是访客
                if(data[i].productClassName=="早餐"){
                  console.log(data[i].count);
                  newArr[j].breakfastCount=data[i].count==null?0:data[i].count;
                  newArr[j].breakfastSum=data[i].sum==null?0:data[i].sum;
                }else if(data[i].productClassName=="午餐"){
                  newArr[j].lunchCount=data[i].count==null?0:data[i].count;
                  newArr[j].lunchSum=data[i].sum==null?0:data[i].sum;
                }else{//晚餐
                  newArr[j].dinnerCount=data[i].count==null?0:data[i].count;
                  newArr[j].dinnerSum=data[i].sum==null?0:data[i].sum;
                }
              }
            }
          }
        }


        //计算全天合计
        newArr.forEach((item,index)=>{
          item.allCount=(item.count==null?0:item.count);//全天次数
          item.allSum=(item.sum==null?0:item.sum);//全天金额
        })
        this.tableData =newArr;
      },
      handleClick(row) {
        console.log(row)
      }
    }
  }
</script>

<style scoped lang="scss">
  .title {
    text-align: center;
    font-size: 18px;
    padding: 20px 0 10px;
    font-weight: bold;

    span {
      margin-left: 10px;
    }
  }

  .upload {
    display: inline-block;
  }

  .button_list {
    margin-bottom: 10px;
  }

  .content {
    text-align: left;
  }

  .el-divider {
    margin: 10px 0;
  }


  .el-form-item {
    margin-bottom: 11px;
  }
</style>
